<template>
    <div class="footer">
        <div class="goTop" v-show="goTop" @click="toTop">
            Top
        </div>
    </div>
</template>

<script>
    import Vue from 'vue';
    import {Icon} from 'vant';

    Vue.use(Icon);
    export default {
        name: "ToTop",
        data() {
            return {
                goTop: false
            }
        },
        mounted() {
            // 此处true需要加上，不加滚动事件可能绑定不成功
            window.addEventListener("scroll", this.handleScroll, true);
        },
        methods: {
            handleScroll() {
                let scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
                scrolltop > 30 ? (this.goTop = true) : (this.goTop = false);
            },
            toTop() {
                let top = document.documentElement.scrollTop || document.body.scrollTop;
                // 实现滚动效果
                const timeTop = setInterval(() => {
                    document.body.scrollTop = document.documentElement.scrollTop = top -= 50;
                    if (top <= 0) {
                        clearInterval(timeTop);
                    }
                }, 10);
            }
        }
    }
</script>

<style scoped>
    .footer .goTop {
        height: 40px;
        width: 40px;
        line-height: 40px;
        text-align: center;
        position: fixed;
        right: 5px;
        bottom: 55px;
        cursor: pointer;
        border-radius: 50%;
        background: #1989fa;
        color: #fff;
    }
</style>
